<?php

declare(strict_types=1);

namespace app\admin\middleware;

use AlibabaCloud\Client\Request\Request;
use app\common\lib\Show;

/**
 * 使用中间件处理是否登录
 * Class Auth
 * @package app\admin\middleware
 */
class Auth
{
    public $accessToken = "";
    public $userId = 0;
    public $username = "";
    public $userRoleId = 0;
    public $userAreaId = 0;

    public function handle(\app\Request $request, \Closure $next)
    {
        $this->accessToken=$request->header('Authori-zation');
        $response = $next($request);
        $allow=['captcha','login'/*,'logout'*/];
        if(in_array($request->pathinfo(),$allow)){
            return $response;
        }
        if(!$this->isLogin()){
            return Show::error([],empty($this->accessToken)?'请先登录':'登录已过期请重新登录',config('status.not_login'));
        }
        return $response;
    }

    /**
     * 判断是否登录
     * @return bool
     */
    public function isLogin(): bool
    {
        $userInfo = cache(config("redis.admin_token_pre") . $this->accessToken);
        if (!$userInfo) {
            return false;
        }
        if (!empty($userInfo['id']) && !empty($userInfo['username']) && !empty($userInfo['roles'])) {
            $this->username = $userInfo['username'];
            $this->userId = $userInfo['id'];
            $this->userRoleId = $userInfo['roles'];
            $this->userAreaId = $userInfo['area_id'];
            return true;
        }
        return false;
    }
}
